<?php
/**
 * Created by PhpStorm.
 * User: server
 * Date: 2018/6/19
 * Time: 10:54
 */

namespace app\index\controller;


use app\index\Controller;
use think\Db;
use think\Validate;

/**
 * @title 订单（模块13）
 * @description 接口说明
 * @group 订单
 * @header name:model_id   default:05 desc:模块id
 * @groupremark 已使用错误码：1130001 1130002 1130003 1130004 1130005 1130006 1130007 1130008 1130009 1130010 1130011 1130012
 */
class Order extends Controller
{


    /**
     * @title 获取订单列表
     * @description 接口说明
     * @author 李锐志
     * @url /index/order/index
     * @param name:token type:string require:1  other: desc:token
     * @param name:driver_user_id type:string require:1  other: desc:用户id
     * @param name:page type:string    other: desc:订单页数
     * @param name:dispatch_group_status type:string    other: desc:订单状态
     *
     * @method ~
     * @return error_id: 1130001 不存在或未填写信息
     * @return  accounts_money:累计结算金额
     * @return list:旅客分组信息@
     * @list title:旅行团名称 id:派单编号 dispatch_id:调配单id num:人数 driver_confirm:司机是否确认 go_date:开始时间 end_date:结束时间 dispatch_group_status:当前分组状态（订单状态） is_settlement:是否结算 settlement_mode:结算方式 settlement_money:结算佣金 settlement_time:结算时间 car_form:用车形式
     */
    public function index()
    {
        $data = input();
//logs('20190215app',$data);
        $h24 = NOW_TIME + 24*3600;

        if(!$data['driver_user_id']){
            $msg['error_id'] = '1130010';
            $msg['message'] = '缺少driver_user_id参数';
            return $this->error($msg);
        }

        //如果有传入派车单状态
        if($data['dispatch_group_status']){
            switch ($data['dispatch_group_status']){
                case 'accounts': // 已结算
                    $map['dtg.dispatch_group_status'] = $data['dispatch_group_status'];
                    $map['dtg.is_reject_settlement'] = 0;//为0时是未拒绝
                    $map['dtg.is_settlement']='1';
                    break;
                case 'achieve': // 已完成
                    $map['dtg.dispatch_group_status'] = $data['dispatch_group_status'];
                    $map['dtg.is_reject_settlement'] = ['in','0,1'];// 为0时是未拒绝
                    break;
                case 'receiving'://已接单
                    $map['dtg.dispatch_group_status'] = $data['dispatch_group_status'];
                    $map['dtg.driver_confirm'] = 1;
                    break;
                default:
                    $map['dtg.dispatch_group_status']=$data['dispatch_group_status'];
            }
        }else{
            //查询未分配的？？？？
            $map['dtg.dispatch_group_status']=array('neq','undistributed');
        }

        $map['dtg.isdelete'] = 0; //未删除
        $map['dtg.is_suspend'] = 1; // 未申请中止

        //获取分页数据
        $listRows = $this->request->param('numPerPage') ? : config("paginate.list_rows");

        //查询派车单数据
        $list = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->where('dtg.driver_user_id',$data['driver_user_id'])
            ->where($map)
            ->order('dtg.id desc')
            ->field("dtg.*,ifnull(dtg.end_date,0) as end_date,if(dtg.end_date,FROM_UNIXTIME(dtg.end_date,'%Y-%m-%d'),null) as end_date_str,ifnull(dtg.go_date,0) as go_date,if(dtg.go_date,FROM_UNIXTIME(dtg.go_date,'%Y-%m-%d' ),null) as go_date_str")
            ->paginate($listRows, false, ['query' => $this->request->get(),"page"=>input("page")]);

        $items = $list->items();

        foreach ($items as $key=>$value){

            //结算状态
            if ($value['is_settlement']){//是否结算
                $items[$key]['settlement_status'] = '已结算';
            }elseif ($value['is_reject_settlement']){
                $items[$key]['settlement_status'] = '结算不通过';
            }elseif($items[$key]['is_apply_settlement']){
                $items[$key]['settlement_status'] = '结算审核中';
            }elseif (empty($value['is_settlement'])&&empty($value['is_reject_settlement'])&&$items[$key]['is_apply_settlement']){
                $items[$key]['settlement_status'] = '未结算';
            }

            //判断出发日期是否小于等于一天
            if($value['go_date'] <= $h24){
                $in24h='true';
            }else{
                $in24h='false';
            }

            if($value['is_pickup'] == 1){

                $order_info = Db::name('order')->where('id',$items[$key]['oid'])->field('id,pick_up_time,pick_up_location')->find();
                $items[$key]['pick_up_time'] = $order_info['pick_up_time'];
                $items[$key]['pick_up_location'] = $order_info['pick_up_location'];

                //旅客人数
                $num = Db::name("order_traveler")
                    ->where('oid',$value['oid'])
                    ->count('id');

                $items[$key]['num'] = $num;

                $items[$key]['num_str'] = $num;

                //获取订单信息旅客
                $travelers=Db::name("order_traveler")
                    ->alias('ot')
                    ->where('oid',$value['oid'])
                    ->field("ot.*,if($in24h,ot.phone,'***********') as phone")
                    ->select();



            }else{
                //旅客人数
                $num = Db::name("dispatch_traveler")
                    ->where('group_id',$value['id'])
                    ->count('traveler_id');

                $items[$key]['num'] = $num;

                $order_nums = Db::name("dispatch_traveler")
                    ->where('group_id',$value['id'])
                    ->group('oid')
                    ->column('count(traveler_id) as num');

                $num_str = "";

                if($order_nums){
                    $num_str=implode('+',$order_nums);
                }

                $items[$key]['num_str']=$num_str;

                //获取订单信息旅客
                $travelers=Db::name("dispatch_traveler")
                    ->alias('dt')
                    ->where('dt.group_id',$value['id'])
                    ->join('tp_order_traveler ot','ot.id=traveler_id','left')
                    ->field("ot.*,if($in24h,ot.phone,'***********') as phone")
                    ->select();
            }

            $items[$key]['travelers']=$travelers;
        }

        if($list){
            //获取累计的已结算金额
            $accounts_money = Db::name('dispatch_traveler_group')
                              ->where("dispatch_group_status",'accounts')
                              ->where("driver_user_id",$data['driver_user_id'])
                              ->where('is_settlement',1) //是否已结算
                              ->where("settlement_money",">",0)
                              ->sum('settlement_money');
            $msg['accounts_money'] = doubleval($accounts_money);
            $msg['list'] = $items;
            $msg['total'] = $list->total();
            $msg['per_page'] = $list->listRows();
            $msg['current_page'] = $list->currentPage();
            $msg['message'] = "获取成功";
            return $this->success($msg);
        }else{
            $msg['error_id'] = "1130001";
            $msg['message'] = "获取失败";
            return $this->error($msg);
        }
    }

    /**
     * @title 获取单个订单
     * @description 接口说明
     * @author 李锐志
     * @url /index/order/query_order
     * @param name:token type:string require:1  other: desc:token
     * @param name:id type:string require:1  other: desc:订单号
     * @method ~
     * @return error_id: 1130009 不存在或未填写信息
     * @return data:旅客分组信息@
     * @data title:旅行团名称 id:派单编号 dispatch_id:调配单id num:人数 driver_confirm:司机是否确认 go_date:开始时间 end_date:结束时间 dispatch_group_status:当前分组状态 is_settlement:是否结算 settlement_mode:结算方式 settlement_money:结算佣金 settlement_time:结算时间 car_form:用车形式
     */
    public function query_order(){
        $data = input();

        $h24 = NOW_TIME+24*3600;

        $result = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->join('dispatch d', 'dtg.dispatch_id=d.id', 'left')
            ->where('dtg.id', $data['id'])
            ->field('dtg.*')
            ->find();

        if($result['go_date']<=$h24){
            $in24h=true;
        }else{
            $in24h=false;
        }

        if($result['is_pickup'] == 1){
            //旅客人数
            $num = Db::name("order_traveler")
                ->where('oid',$result['oid'])
                ->count('id');

            $result['num'] = $num;

            $result['num_str'] = $num;

            //获取订单信息旅客
            $travelers = Db::name("order_traveler")
                ->alias('ot')
                ->where('oid',$result['oid'])
                ->field("ot.*,if($in24h,ot.phone,'***********') as phone")
                ->select();
        }else{
            //旅客人数
            $num=Db::name("dispatch_traveler")
                ->where('group_id',$result['id'])
                ->count('traveler_id');

            $result['num'] = $num;

            $order_nums = Db::name("dispatch_traveler")
                ->where('group_id',$result['id'])
                ->group('oid')
                ->column('count(traveler_id) as num');

            $num_str="";

            if($order_nums){
                $num_str=implode('+',$order_nums);
            }

            $result['num_str'] = $num_str;

            $travelers = Db::name("dispatch_traveler")
                ->where('group_id',$result['id'])
                ->join('tp_order_traveler ot','ot.id=traveler_id','left')
                ->field("ot.*,if({$in24h},ot.phone,'***********') as phone\"")
                ->select();
        }

        $result['travelers'] = $travelers;

        if ($result) {
            $msg['data'] = $result;
            return $this->success($msg);
        } else {
            $msg['error_id'] = '1130009';
            $msg['message'] = '不存在或未填写信息';
            return $this->error($msg);
        }
    }

    /**
     * @title 获取所有派单中的订单列表
     * @description 接口说明
     * @author 李锐志
     * @url /index/order/send_order
     * @param name:token type:string require:1  other: desc:token
     * @param name:driver_user_id type:string require:1  other: desc:司机用户id
     * @method ~
     * @return error_id: 1130008 不存在或未填写信息
     * @return list:旅客分组信息@
     * @list title:旅行团名称 id:派单编号 dispatch_time:分配时间 proceed_time:进行中时间 settlement_apply_time:结算申请时间 settlement_time:结算完成时间 dispatch_id:调配单id num:人数 driver_confirm:司机是否确认 go_date:开始时间 end_date:结束时间  dispatch_group_status:当前分组状态 is_settlement:是否结算 settlement_mode:结算方式 settlement_money:结算佣金 settlement_time:结算时间 car_form:用车形式
     */
    public function send_order()
    {

        $data = input();

        $listRows = $this->request->param('numPerPage') ? : config("paginate.list_rows");

        $list = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->join('dispatch d', 'dtg.dispatch_id=d.id', 'left')
            ->where('dispatch_group_status', 'sendorders')
            ->where('dtg.driver_user_id', $data['driver_user_id'])
            ->field("dtg.*,ifnull(dtg.end_date,0) as end_date,if(dtg.end_date,FROM_UNIXTIME(dtg.end_date,'%Y-%m-%d'),null) as end_date_str,ifnull(dtg.go_date,0) as go_date,if(dtg.go_date,FROM_UNIXTIME(dtg.go_date,'%Y-%m-%d' ),null) as go_date_str")
            ->paginate($listRows, false, ['query' => $this->request->get(),"page"=>input("page")]);

        $items=$list->items();

        foreach ($items as $key=>$value){

            if($value['is_pickup'] == 1){
                //旅客人数
                $num = Db::name("order_traveler")
                    ->where('oid',$value['oid'])
                    ->count('id');

                $items[$key]['num'] = $num;

                $items[$key]['num_str'] = $num;

                //获取订单信息旅客
                $travelers = Db::name("order_traveler")
                            ->where('oid',$value['oid'])
                            ->select();

            }else{
                //旅客人数
                $num = Db::name("dispatch_traveler")
                        ->where('group_id',$value['id'])
                        ->count('traveler_id');

                $items[$key]['num'] = $num;

                $order_nums = Db::name("dispatch_traveler")
                            ->where('group_id',$value['id'])
                            ->group('oid')
                            ->column('count(traveler_id) as num');

                $num_str = "";

                if($order_nums){
                    $num_str = implode('+',$order_nums);
                }

                $items[$key]['num_str'] = $num_str;

                //旅客
                $travelers = Db::name("dispatch_traveler")
                            ->alias('dt')
                            ->where('dt.group_id',$value['id'])
                            ->join('tp_order_traveler ot','ot.id=dt.traveler_id','left')
                            ->field("ot.*")
                            ->select();
            }

            $items[$key]['travelers'] = $travelers;
        }

        if ($list) {
            $msg['list'] = $items;
            $msg['total'] = $list->total();
            $msg['per_page'] = $list->listRows();
            $msg['current_page'] = $list->currentPage();
            $msg['message'] = "获取成功";
            return $this->success($msg);
        } else {
            $msg['error_id'] = '1130008';
            $msg['message'] = '不存在或未填写信息';
            return $this->error($msg);
        }
    }

    /**
     * @title 拒单操作
     * @description 接口说明
     * @author 李锐志
     * @url /index/order/reject
     * @param name:token type:string require:1  other: desc:token
     * @param name:id type:int require:1  other: desc:派单编号
     * @param name:reason type:int require:1  other: desc:拒单原因
     * @method ~
     * @return error_id: 1130004 拒单失败
     */
    public function reject()
    {

        $data = input();

        $group=Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->find();

        if(!$group){
            $msg['error_id'] = '1130004';
            $msg['message'] = '不存在或未填写信息';
            return $this->error($msg);
        }

        if($group['dispatch_group_status']!='sendorders'){
            $msg['error_id'] = '1130004';
            $msg['message'] = '状态冲突';
            return $this->error($msg);
        }

        $update['dispatch_group_status']='undistributed';
        $update['driver_confirm']=false;
        $update['isreject']=false;
        $update['reject_reason']=$data['reason'];
        $update['reject_time']=NOW_TIME;

        //恢复分组状态，并记录拒单的原因
        $re=Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->update($update);

        //让司机恢复不是服务状态
        Db::name('driver')->where('user_id',$group['driver_user_id'])->update(array('inservice'=>false));

        //查询该司机的用户信息
        $driverUser = Db::name('admin_user')->where('id',$group['driver_user_id'])->find();
        if (!$driverUser){

            $msg['error_id'] = 1130004;
            $msg['message'] = '不存在司机的用户信息';
            return $this->error($msg);

        }

        //记录司机的拒单次数
        //从司机表获取司机信息
        $driverUserInfo = Db::name('driver')->where('user_id',$group['driver_user_id'])->find();

        if ($driverUserInfo['number_of_refusals']){//有值
            $number_of_refusals = $driverUserInfo['number_of_refusals'] + 1;
            $up = Db::name('driver')->where('user_id',$driverUser['id'])->update(['number_of_refusals'=>$number_of_refusals]);
            logs('up201901241808',$up);
        }else{
            $up = Db::name('driver')->where('user_id',$driverUser['id'])->update(['number_of_refusals'=>1]);
            logs('up201901241808',$up);
        }

        //记录司机的拒单原因
        $insert = [
            'user_id' => $group['driver_user_id'],
            'driver_id'=>$driverUser['id'],
            'group_id'=>$group['id'],
            'title'=>$group['title'],
            'rejection_reason'=>htmlspecialchars($data['reason']),
            'create_time' => time(),
            'group_status' => 'sendorders'
        ];
        $drd = DB::name('driver')
            ->where('user_id',$group['driver_user_id'])
            ->field('vehicle_level,driver_rank_id')
            ->find();
        $realname = Db::name('admin_user')->where('id',$group['driver_user_id'])->value('realname');
        $dr_rank_id= Db::name('driver_rank')->where('id',$drd['driver_rank_id'])->value('name');
        if($group['is_pickup'] == 0){
            $namt = Db::name('order_traveler')->where('group_id',$group['id'])->field('name')->select();
            foreach($namt as $k => $v) {
                $guest_name[] = $v['name'];
            }
            if(!empty($guest_name)) {
                $datau['guest_name'] = implode("+", $guest_name);
            } else {
                $datau['guest_name'] = null;
            }
            $guest_names =  rtrim($datau['guest_name'],'+');
        } else {
            $namt = Db::name('order_traveler')->where('oid',$data['oid'])->field('name')->select();
            foreach($namt as $k => $v) {
                $guest_name[] = $v['name'];
            }
            if(!empty($guest_name)) {
                $datau['guest_name'] = implode("+", $guest_name);
            } else {
                $datau['guest_name'] = null;
            }
            $guest_names =  rtrim($datau['guest_name'],'+');
        }
        $title = Db::name('route')->where('id',$group['route_id'])->value('title');
        $inserts = [
            'dispatch_id'=>$group['id'],
            'title'=>$title,
            'start_time'=>$group['go_date'],
            'end_time'=>$group['end_date'],
            'car_form'=>$group['car_form'],
            'vehicle_level'=>$drd['vehicle_level'],
            'realname'=>$realname,
            'remark'=>$group['remark'],
            'dr_rank_name'=>$dr_rank_id,
            'guest_name'=>$guest_names,
            'guest_num'=>$group['num'],
            'rejection_reason'=>htmlspecialchars($data['reason']),
            'create_time' => time(),
            'is_rejection' => 1,
        ];
        //把更换司机原因添加进表
        $insertGetIds = Db::name('driver_rejection_write')->strict(false)->insertGetId($inserts);

        $insertGetId = Db::name('driver_refused')->strict(false)->insertGetId($insert);
        logs('up201901241808',$insertGetId);
        if ($re) {
            $time = time();
            set_info($driverUser['id'],'取消订单',"你的订单名称为{$group['title']}的订单于{$time}取消成功",'system_ordinary_info',array('dispatch_traveler_group_id' => $group['id']));
            $msg['message'] = "拒单成功";
            return $this->success($msg);
        } else {
            $msg['error_id'] = '1130004';
            $msg['message'] = '拒单失败';
            return $this->error($msg);
        }
    }

    public function reject_beifen()
    {

        $data = input();
        $group=Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->find();
        if(!$group){
            $msg['error_id'] = '1130004';
            $msg['message'] = '不存在或未填写信息';
            return $this->error($msg);
        }
        if($group['dispatch_group_status']!='sendorders'){
            $msg['error_id'] = '1130004';
            $msg['message'] = '状态冲突';
            return $this->error($msg);
        }
        $update['dispatch_group_status']='undistributed';
        $update['driver_confirm']=false;
        $update['isreject']=false;
        $update['reject_reason']=$data['reason'];
        $update['reject_time']=NOW_TIME;

        //恢复分组状态，并记录拒单的原因
        $re=Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->update($update);
        //让司机恢复不是服务状态
        Db::name('driver')->where('user_id',$group['driver_user_id'])->update(array('inservice'=>false));
        //查询该司机的用户信息
        if ($re) {
            $msg['message'] = "拒单成功";
            return $this->success($msg);
        } else {
            $msg['error_id'] = '1130004';
            $msg['message'] = '拒单失败';
            return $this->error($msg);
        }
    }

    /**
     * @title 中止订单操作
     * @description 接口说明
     * @author 邓汉炜
     * @url /index/order/suspension
     * @param name:token type:string require:1  other: desc:token
     * @param name:id type:int require:1  other: desc:派单编号
     * @param name:suspend_reason type:string require:1  other: desc:拒单原因
     * @method ~
     * @return error_id: 1130004 中止订单失败 1130005 校验失败
     * @return list:返回该派单处理信息@
     * @list id:派单编号 suspend_reason:申请的中止原因 is_suspend:是否申请中止,2为已申请中止
     */
    public function suspension()
    {
        $data = input();

        //校验数据
        $rule = [
            'token'=>'require',
            'id'=>'require',
            'suspend_reason'=>'require',
        ];
        $mvg = [
            'token.require' => '缺少token',
            'id.require' => '缺少派单编号',
            'suspend_reason.require' => '中止订单原因不能为空'
        ];
        $validate = new Validate($rule,$mvg);
        $result = $validate->check($data);
        if (!$result){
            $msg['error_id'] = 1130005;
            $msg['message'] = $validate->getError();
            return $this->error($msg);
        }

        //根据分组id查找该分组信息
        $group = Db::name('dispatch_traveler_group')->where('id',$data['id'])->find();

        if (!$group){
            $msg['error_id'] = 1130004;
            $msg['message'] = '不存在该派单信息';
            return $this->error($msg);
        }elseif ($group['dispatch_group_status'] != 'proceed'){
            $msg['error_id'] = 1130004;
            $msg['message'] = '状态冲突';
            return $this->error($msg);
        }elseif ($group['is_suspend'] == 2){
            $msg['error_id'] = 1130004;
            $msg['message'] = '你已经申请中止该车队';
            return $this->error($msg);
        }

        //查询司机用户信息
        $driverName = Db::name('admin_user')->where('id',$group['driver_user_id'])->value('realname');

        $insert = [
            'suspend_reason' => $data['suspend_reason'],//记录申请中止原因
            'is_suspend' => 2,//该分组恢复未确认状态
            'suspension_time' => time(),//申请中止订单时间
            'old_driver_user_id' => $group['driver_user_id'],
            'old_driver_user_name' => $driverName,
        ];

        //更新改派单信息
        $up = Db::name('dispatch_traveler_group')->where('id',$group['id'])->strict(false)->update($insert);

        if ($up){
            $msg['list'] = Db::name('dispatch_traveler_group')->where('id',$group['id'])->field('id,suspend_reason,is_suspend')->find();
            //发送信息
            set_info($group['driver_user_id'],'取消进行中订单',"您申请派单编号为{$data['id']}的派单,正在处理",'dispatch_traveler_group',['dispatch_traveler_group_id'=>$data['id']]);
            $msg['message'] = '申请中止订单成功';
            return $this->success($msg);
        }else{
            $msg['error_id'] = 1130004;
            $msg['message'] = '申请中止订单失败';
            return $this->error($msg);
        }
    }

    ///////以下为修改完的接口////////////////
    /**
     * @title 接单操作
     * @description 接口说明
     * @author 李锐志
     * @url /index/order/accept
     * @param name:token type:string require:1  other: desc:token
     * @param name:id type:int require:1  other: desc:派单编号
     * @method ~
     * @return list:该订单的所有旅客信息@
     * @list id:旅客id name:姓名 phone:手机号 id_card:身份证 adress:地址 oid:订单id group_id:派单编号
     * @return error_id: 1130002 订单状态修改失败，说明该订单已被接单
     * @return error_id: 1130003 不存在或未填写信息
     */
    public function accept()
    {
        //获取数据
        $data = input();
        $group = Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->find();

        if(!$group){
            $msg['error_id'] = '1130003';
            $msg['message'] = '不存在或未填写信息';
            return $this->error($msg);
        }

        if($group['dispatch_group_status'] == 'receiving' && $group['driver_confirm'] == 1){
            $msg['error_id'] = '1130002';
            $msg['message'] = '订单已处理';
            return $this->error($msg);
        }

        $update['dispatch_group_status'] = 'receiving';
        $update['driver_confirm'] = true;
        $update['receiving_time'] = NOW_TIME;

        $re = Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->update($update);

        //如果不是接机订单
        if($group['is_pickup'] != '1'){
            if ($re) {
                // 司机接受派单，同步住宿派单
                $group_id = $data['id']; // 派单id
                // 从订单旅客表获取派单旅客数据,并且有住宿要求的旅客
                $groupTravel = Db::name('order_traveler')->where('group_id',$group_id)->where('isaccommodation','包含住宿')->select();
                //  查询派单数据
                $groupInfo = Db::name('dispatch_traveler_group')->where('id',$group_id)->find();
                // 查找司机信息
                $driver = Db::name('driver')->where('user_id',$groupInfo['driver_user_id'])->find();
                if ($groupTravel  && empty($group['reverse_id'])){
                    // 同步住宿派单
                    $insert = [
                        'driver_id' => $driver['id'],
                        'driver_user_id' =>$groupInfo['driver_user_id'],
                        'number_of_guests' =>count($groupTravel),
                        'departure_date' =>$groupInfo['go_date'],
                        'group_id' =>$group_id,
                        'car_form' =>$groupInfo['car_form'],
                        'create_time' =>time(),
                    ];
                    // 添加到表里
                    $addId = Db::name('portion_traveler')->strict(false)->insertGetId($insert);
                    logs('paidan',$addId);
                    //获取订单ids
                    $order_ids = Db::name('order_traveler')->group('oid')->where('group_id',$group_id)->field('id,oid,group_id')->select();

                    //更改订单状态
                    if(count($order_ids)>1){
                        // order_status issue已出单
                        // dispose_status normal_travel:正常出行
                        $update['order_status'] = 'issue';
                        $update['dispose_status'] = 'normal_travel';
                        foreach ($order_ids as $ok => $ov){
                            Db::name('order')->strict(false)->where('id',$ov['oid'])->update($update);
                        }
                    }

                    logs('paidan',$addId);
                }
                $msg['message'] = "接单成功";
                return $this->success($msg);
            } else {
                $msg['error_id'] = '1130003';
                $msg['message'] = '不存在或未填写信息';
                return $this->error($msg);
            }
        }else {  //如果是接机订单
            //接机单不需要同步住宿
            $msg['message'] = "接单成功";
            return $this->success($msg);
        }
    }

    /**
     * @title 订单完成
     * @description 接口说明
     * @author 李锐志
     * @url /index/order/accomplish
     * @param name:token type:string require:1  other: desc:token
     * @param name:id type:int require:1  other: desc:派单编号
     * @method ~
     * @return list:订单分组基本信息@
     * @list order_status:进行状态 id:派单编号 num:人数 go_date:开始时间 end_date:结束时间
     * @return error_id: 1130007 状态修改失败
     */
    public function accomplish()
    {
        $data = input();

        $group=Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->find();

        if(!$group){
            $msg['error_id'] = '1130007';
            $msg['message'] = '不存在或未填写信息';
            return $this->error($msg);
        }

        //是否在结束时间之后
        if($group['end_date']&&$group['end_date']>time()){
            $msg['error_id'] = '1130008';
            $msg['message'] = '请在结束时间之后确认订单';
            return $this->error($msg);
        }

        if($group['dispatch_group_status']!='proceed'){
            $msg['error_id'] = '1130009';
            $msg['message'] = '状态冲突';
            return $this->error($msg);
        }

        $update['dispatch_group_status']='achieve';
        $update['achieve_time']=NOW_TIME;

        $re=Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->update($update);

        $dispatch =  Db::name('dispatch_traveler_group')
            ->where('id','not in', $data['id'])
            ->where('dispatch_group_status','in','sendorders,proceed')
            ->where('driver_user_id',$group['driver_user_id'])
            ->select();

        //释放司机
        if (!count($dispatch)){
            Db::name('driver')->where('user_id',$group['driver_user_id'])->update(array('inservice'=>false));
        }
        $date_time=date("Y-m-d H:i:s",NOW_TIME);
        set_info($group['driver_user_id'], '已经完成',"{$date_time} 你的订单已经完成，订单编号为{$data['id']},结算金额为{$group['settlement_money']}", 'dispatch_traveler_group', array('dispatch_traveler_group_id' => $data['id']));

        if ($re) {
            $msg['message'] = "操作成功";
            return $this->success($msg);
        } else {
            $msg['error_id'] = '1130007';
            $msg['message'] = '操作失败';
            return $this->error($msg);
        }
    }

    /**
     * @title 申请结算
     * @description 接口说明
     * @author 李锐志
     * @url /index/order/apply
     * @param name:token type:string require:1  other: desc:token
     * @param name:id type:int require:1  other: desc:派单编号
     * @method ~
     * @return error_id: 1130005 结算申请失败
     * @return error_id: 1130006 不可重复申请
     */
    public function apply()
    {
        $data = input();
        $result = Db::name('settlement')
            ->field('id')
            ->where('group_id', $data['id'])
            ->find();

        if ($result) {
            $msg['error_id'] = '1130006';
            $msg['message'] = '不可重复申请';
            return $this->error($msg);
        }

        $group=Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->find();
        if(!$group){
            $msg['error_id'] = '1130006';
            $msg['message'] = '不存在或未填写信息';
            return $this->error($msg);
        }
        if($group['dispatch_group_status']!='achieve'){
            $msg['error_id'] = '1130006';
            $msg['message'] = '状态冲突';
            return $this->error($msg);
        }
        $update['settlement_apply_time']=NOW_TIME;

        $re=Db::name('dispatch_traveler_group')
            ->where('id', $data['id'])
            ->update($update);

        if ($re) {
            $data['create_time'] = time();
            $data['group_id']=$data['id'];
            unset($data['id']);
            $status = Db::name('settlement')
                ->insert($data);

            if (!$status) {
                $msg['error_id'] = '1130005';
                $msg['message'] = '结算申请失败';
                return $this->error($msg);
            } else {
                $msg['message'] = '申请成功';
                return $this->success($msg);
            }
        } else {
            $msg['error_id'] = '1130006';
            $msg['message'] = '操作失败';
            return $this->error($msg);
        }

    }

    /**
     * @title 结算订单删除
     * @description 接口说明
     * @author 梁敏
     * @url /index/order/delete
     * @param name:token type:string require:1  other: desc:token
     * @param name:id type:int require:1  other: desc:派单编号
     * @method ~
     * @return error_id: 1130005 结算申请失败
     * @return error_id: 1130006 不可重复申请
     */
    public function delete()
    {

        $group_id = input('id');

        $dispatch_traveler_group = Db::name('dispatch_traveler_group')->where('id',$group_id)->field('id,isdelete,dispatch_group_status,is_settlement')->find();

        if(!$dispatch_traveler_group){
            $msg['error_id'] = '1130012';
            $msg['message'] = '不存在或未填写信息';
            return $this->error($msg);
        }

        if($dispatch_traveler_group['dispatch_group_status'] != 'accounts'){
            $msg['error_id'] = '1130013';
            $msg['message'] = '该派车单当前状态不可删除';
            return $this->error($msg);
        }

        if($dispatch_traveler_group['is_settlement'] != 1){
            $msg['error_id'] = '1130014';
            $msg['message'] = '该派车单当前状态不可删除';
            return $this->error($msg);
        }

        if($dispatch_traveler_group['isdelete'] == '1'){
            $msg['message'] = '该派车单已删除';
            return $this->error($msg);
        }

        $data['isdelete'] = 1;

        $res = Db::name('dispatch_traveler_group')->strict(false)->where('id',$group_id)->update($data);

        if($res){
            $msg['message'] = '操作成功';
            return $this->success($msg);
        }else{
            $msg['error_id'] = '1130011';
            $msg['message'] = '操作失败';
            return $this->error($msg);
        }

    }
}